package com.hema.auction.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.google.gson.Gson;
import com.hema.auction.R;
import com.hema.auction.base.BaseRechargeActivity;
import com.hema.auction.bean.AddressInfo;
import com.hema.auction.bean.OrderInfo;
import com.hema.auction.event.PayResultEvent;
import com.hema.auction.http.HttpTag;
import com.hema.auction.http.biz.HttpManager;
import com.hema.auction.utils.Constant;
import com.hema.auction.utils.GlideUtils;
import com.hema.auction.utils.Utils;
import com.hema.auction.widget.view.TitleView;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 描述:确认订单
 * 作者:john
 */
public class ConfirmOrderActivity extends BaseRechargeActivity {

    @BindView(R.id.title_view)
    TitleView titleView;
    @BindView(R.id.tv_address_tips)
    TextView tvAddressTips;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.ll_address)
    LinearLayout llAddress;
    @BindView(R.id.iv_img)
    ImageView ivImg;
    @BindView(R.id.tv_market_price)
    TextView tvMarketPrice;
    @BindView(R.id.tv_auction_price_title)
    TextView tvAuctionPriceTitle;
    @BindView(R.id.tv_auction_price)
    TextView tvAuctionPrice;
    @BindView(R.id.tv_dealer_price_title)
    TextView tvDealerPriceTitle;
    @BindView(R.id.tv_dealer_price)
    TextView tvDealerPrice;
    @BindView(R.id.tv_pay)
    TextView tvPay;
    @BindView(R.id.cb_gw)
    CheckBox cbGw;
    @BindView(R.id.cx_line)
    View cxLine;
    @BindView(R.id.et_remark)
    EditText etRemark;
    @BindView(R.id.tv_payment_amount)
    TextView tvPaymentAmount;
    @BindView(R.id.rb_alipay)
    RadioButton rbAlipay;
    @BindView(R.id.rb_wechat)
    RadioButton rbWechat;

    private String orderId, transId;
    private OrderInfo orderInfo;
    private boolean isCjBuy, isCjBuyPay;
    private float payPrice;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_confirm_order);
        ButterKnife.bind(this);
        orderId = getIntent().getStringExtra(Constant.EXTRA_ORDER_ID);
        isCjBuy = getIntent().getBooleanExtra(Constant.EXTRA_CJ_BUY, false);
        isCjBuyPay = getIntent().getBooleanExtra(Constant.EXTRA_CJ_BUY_PAY, false);
        orderInfo = getIntent().getParcelableExtra(Constant.EXTRA_ORDER_INFO);
        if (orderInfo == null) {
            showProgressDialog();
            HttpManager.getInstance(this).orderDetail(orderId, this);
        } else {
            orderId = orderInfo.getOrderId();
            init();
        }
        rbAlipay.setOnClickListener(view -> {
            rbAlipay.setChecked(true);
            rbWechat.setChecked(false);
            payType = "alipay_h5";
        });
        rbWechat.setOnClickListener(view -> {
            payType = "wechat_h5";
            rbWechat.setChecked(true);
            rbAlipay.setChecked(false);
        });
    }

    private void init() {
        tvMarketPrice.setText(Utils.priceUnitFormat(this, orderInfo.getPrice()));//市场价
        GlideUtils.load(this, orderInfo.getGoodPic(), ivImg);
        if (isCjBuyPay) {

            tvPay.setText("差价购买");
            tvAuctionPriceTitle.setText(R.string.use_shopping_coin);
            titleView.setTitle(tvPay.getText().toString());
            if (isCjBuy) {
                tvDealerPrice.setText(Utils.priceUnitFormat(this, orderInfo.getFinalPrice())); //实付价格
                payPrice = orderInfo.getFinalPrice();
            } else {
                payPrice = orderInfo.getPrice();
                tvDealerPrice.setText(Utils.priceUnitFormat(this, orderInfo.getPrice())); //实付价格
            }
            tvAuctionPrice.setText("-" + Utils.priceUnitFormat(this, orderInfo.getGwPrice()));//使用购物币
            tvDealerPriceTitle.setText(R.string.paid_price_format);
            cbGw.setVisibility(View.VISIBLE);
            cxLine.setVisibility(View.VISIBLE);
            cbGw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                        payPrice = isCjBuy ? orderInfo.getFinalPrice() : orderInfo.getPrice() - orderInfo.getGwPrice();
                        if (payPrice < 0)
                            payPrice = 0;
                        tvDealerPrice.setText(Utils.priceUnitFormat(ConfirmOrderActivity.this, payPrice));
                    } else {
                        payPrice = isCjBuy ? orderInfo.getFinalPrice() : orderInfo.getPrice();
                        tvDealerPrice.setText(Utils.priceUnitFormat(ConfirmOrderActivity.this, payPrice));
                    }
                    tvPaymentAmount.setText(String.valueOf(payPrice));
                }
            });

            if (orderInfo.getIsGwPriceLock() == 0) {//购物币是否已锁定(0否，1是)锁定了就没有勾选的按钮
                cbGw.setVisibility(View.VISIBLE);
            } else {
                cbGw.setVisibility(View.GONE);
                payPrice = isCjBuy ? orderInfo.getFinalPrice() : orderInfo.getPrice() - orderInfo.getGwPrice();
                if (payPrice < 0)
                    payPrice = 0;
                tvDealerPrice.setText(Utils.priceUnitFormat(ConfirmOrderActivity.this, payPrice));
            }
        } else {
            tvAuctionPrice.setText(Utils.priceUnitFormat(this, orderInfo.getFinalPrice()));//拍卖价
            tvDealerPrice.setText(Utils.priceUnitFormat(this, orderInfo.getFinalPrice()));//成交价
            payPrice = orderInfo.getFinalPrice();
            cbGw.setVisibility(View.GONE);
        }
        tvPaymentAmount.setText(String.valueOf(payPrice));
        if (!Utils.isEmpty(orderInfo.getAddress())) {
            tvAddressTips.setVisibility(View.GONE);
            llAddress.setVisibility(View.VISIBLE);
            tvName.setText(getString(R.string.addressee, orderInfo.getConsignee()));
            tvPhone.setText(orderInfo.getCPhone());
            tvAddress.setText(getString(R.string.delivery_address, orderInfo.getAddress()));
        } else {
            tvAddressTips.setVisibility(View.VISIBLE);
            llAddress.setVisibility(View.GONE);
        }


    }

    @OnClick({R.id.tv_pay, R.id.tv_address_tips, R.id.ll_address})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_pay:
//                isAutoDismissDialog = false;
//                showProgressDialog();
                if(Utils.isEmpty(tvName.getText().toString())||
                        Utils.isEmpty(tvPhone.getText().toString())||Utils.isEmpty(tvAddress.getText().toString())){
                    showToastSafe("请先完善收货信息");
                }else {
                    if (isCjBuyPay)
                        HttpManager.getInstance(this).cjPay(payPrice, orderInfo.getOrderId(),
                                orderInfo.getGoodId(), cbGw.isChecked() ? 1 : 0, payType, etRemark.getText().toString(), this);
                    else
                        HttpManager.getInstance(this).myAuctionPay(payPrice, orderInfo.getOrderId(), payType, etRemark.getText().toString(), this);
                }
                break;
            case R.id.tv_address_tips:
            case R.id.ll_address:
                intentToForResult(AddressActivity.class, Constant.REQUEST_CODE_ADDRESS);
                break;
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == Constant.REQUEST_CODE_ADDRESS) {
            AddressInfo info = data.getParcelableExtra(Constant.EXTRA_ADDRESS_INFO);
            if (info != null) {
                tvName.setText(getString(R.string.addressee, info.getName()));
                tvPhone.setText(info.getPhone());
                tvAddress.setText(getString(R.string.delivery_address, info.getArea() + info.getAddress()));
                tvAddressTips.setVisibility(View.GONE);
                llAddress.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    protected void onSuccess(HttpTag httpTag, Call call, JSONObject result) {
        super.onSuccess(httpTag, call, result);
        switch (httpTag) {
            case TAG_ORDER_DETAIL:
                try {
                    if (result.getInt("errcode") == 0) {
                        orderInfo = new Gson().fromJson(result.getJSONObject("data").toString(), OrderInfo.class);
                        init();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case TAG_DO_ORDER:
                try {
                    if (result.getInt("errcode") == 0) {
                        JSONObject data = result.getJSONObject("data");
                        transId = data.getString("transid");
                        startPay(isCjBuyPay ? 4 : 2, transId,payPrice);
//                        orderSn = data.getString("orderSn");
//                        String payUrl = data.getString("payUrl");
//                        toPay(isCjBuyPay ? 4 : 2, payUrl);
                    } else {
                        showToastSafe(result);
                        dismissProgressDialog();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    dismissProgressDialog();
                }
                break;
        }
    }

    @Override
    protected void paySuccess() {
        super.paySuccess();
        if (isCjBuyPay) {
            EventBus.getDefault().post(new PayResultEvent(4));
        } else {
            EventBus.getDefault().post(new PayResultEvent(2));
        }
        finish();
    }
}
